package com.example.dao;

import com.example.domain.Order;
import com.example.domain.OrderItem;
import com.example.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {
    
    /**
     * 创建订单
     */
    public int createOrder(Order order) throws SQLException {
        String sql = "INSERT INTO tb_order (order_no, user_id, total_amount, product_count, status, receiver_name, receiver_phone, receiver_address) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            stmt.setString(1, order.getOrder_no());
            stmt.setInt(2, order.getUser_id());
            stmt.setDouble(3, order.getTotal_amount());
            stmt.setInt(4, order.getProduct_count());
            stmt.setInt(5, order.getStatus());
            stmt.setString(6, order.getReceiver_name());
            stmt.setString(7, order.getReceiver_phone());
            stmt.setString(8, order.getReceiver_address());
            
            stmt.executeUpdate();
            
            // 获取生成的订单ID
            rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                return rs.getInt(1);
            }
            return -1;
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
    }
    
    /**
     * 根据用户ID获取订单列表
     */
    public List<Order> getOrdersByUserId(int userId) throws SQLException {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM tb_order WHERE user_id = ? ORDER BY created_at DESC";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, userId);
            rs = stmt.executeQuery();
            
            while (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("id"));
                order.setOrder_no(rs.getString("order_no"));
                order.setUser_id(rs.getInt("user_id"));
                order.setTotal_amount(rs.getDouble("total_amount"));
                order.setProduct_count(rs.getInt("product_count"));
                order.setStatus(rs.getInt("status"));
                order.setReceiver_name(rs.getString("receiver_name"));
                order.setReceiver_phone(rs.getString("receiver_phone"));
                order.setReceiver_address(rs.getString("receiver_address"));
                order.setPayment_method(rs.getString("payment_method"));
                order.setPayment_time(rs.getTimestamp("payment_time"));
                order.setDelivery_time(rs.getTimestamp("delivery_time"));
                order.setComplete_time(rs.getTimestamp("complete_time"));
                order.setCreated_at(rs.getTimestamp("created_at"));
                order.setUpdated_at(rs.getTimestamp("updated_at"));
                orders.add(order);
            }
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
        return orders;
    }
    
    /**
     * 根据订单ID获取订单详情
     */
    public Order getOrderById(int orderId) throws SQLException {
        String sql = "SELECT * FROM tb_order WHERE id = ?";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, orderId);
            rs = stmt.executeQuery();
            
            if (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("id"));
                order.setOrder_no(rs.getString("order_no"));
                order.setUser_id(rs.getInt("user_id"));
                order.setTotal_amount(rs.getDouble("total_amount"));
                order.setProduct_count(rs.getInt("product_count"));
                order.setStatus(rs.getInt("status"));
                order.setReceiver_name(rs.getString("receiver_name"));
                order.setReceiver_phone(rs.getString("receiver_phone"));
                order.setReceiver_address(rs.getString("receiver_address"));
                order.setPayment_method(rs.getString("payment_method"));
                order.setPayment_time(rs.getTimestamp("payment_time"));
                order.setDelivery_time(rs.getTimestamp("delivery_time"));
                order.setComplete_time(rs.getTimestamp("complete_time"));
                order.setCreated_at(rs.getTimestamp("created_at"));
                order.setUpdated_at(rs.getTimestamp("updated_at"));
                return order;
            }
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
        return null;
    }
    
    /**
     * 创建订单项
     */
    public void createOrderItem(OrderItem orderItem) throws SQLException {
        String sql = "INSERT INTO tb_order_item (order_id, product_id, product_name, price, quantity, subtotal) VALUES (?, ?, ?, ?, ?, ?)";
        Connection conn = null;
        PreparedStatement stmt = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, orderItem.getOrder_id());
            stmt.setInt(2, orderItem.getProduct_id());
            stmt.setString(3, orderItem.getProduct_name());
            stmt.setDouble(4, orderItem.getPrice());
            stmt.setInt(5, orderItem.getQuantity());
            stmt.setDouble(6, orderItem.getSubtotal());
            stmt.executeUpdate();
        } finally {
            DBUtil.closeStatement(stmt);
            DBUtil.closeConnection(conn);
        }
    }
    
    /**
     * 根据订单ID获取订单项列表
     */
    public List<OrderItem> getOrderItemsByOrderId(int orderId) throws SQLException {
        List<OrderItem> orderItems = new ArrayList<>();
        String sql = "SELECT * FROM tb_order_item WHERE order_id = ?";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, orderId);
            rs = stmt.executeQuery();
            
            while (rs.next()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setId(rs.getInt("id"));
                orderItem.setOrder_id(rs.getInt("order_id"));
                orderItem.setProduct_id(rs.getInt("product_id"));
                orderItem.setProduct_name(rs.getString("product_name"));
                orderItem.setPrice(rs.getDouble("price"));
                orderItem.setQuantity(rs.getInt("quantity"));
                orderItem.setSubtotal(rs.getDouble("subtotal"));
                orderItems.add(orderItem);
            }
        } finally {
            DBUtil.closeAll(rs, stmt, conn);
        }
        return orderItems;
    }
}